package com.example.yan_music.view;

import android.animation.AnimatorSet;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.icu.util.Calendar;
import android.os.Bundle;

import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.yan_music.R;
import com.example.yan_music.adapter.BannerImageAdapter;
import com.example.yan_music.adapter.MainViewPagerAdapter;
import com.example.yan_music.adapter.RcvRecommendAdapter;
import com.example.yan_music.adapter.RcvSearchAdapter;
import com.example.yan_music.base.fragment.BaseFragment;
import com.example.yan_music.bean.wangyi.RecommendSongList;
import com.example.yan_music.contract.IMainContract;
import com.example.yan_music.event.ReplaceViewPagerFragmentEvent;
import com.example.yan_music.presenter.IMainPresenterImp;
import com.example.yan_music.service.PlayerService;
import com.example.yan_music.utils.SharePreferenceUtil;
import com.example.yan_music.utils.TextFontUtils;
import com.example.yan_music.utils.XLog;
import com.example.yan_music.utils.XToast;
import com.example.yan_music.utils.statusbar.StatusBarUtil;
import com.example.yan_music.view.fragment.ListDetailFragment;
import com.example.yan_music.view.fragment.SearchFragment;
import com.example.yan_music.widge.MarqueeTextView;
import com.google.android.material.navigation.NavigationView;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.transformer.ZoomOutPageTransformer;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 主活动的主碎片
 * 包含了主要UI
 * <p>
 * 分为 T（顶部） M（中部） B（底部） 部分
 * </p>
 * <p>
 * T层
 * 1.点击设置呼出左侧滑栏 （完成）
 * 2.点击搜索跳转到SearchFragment  （完成）
 * 3.点击头像跳转到用户中心  （未完成）
 * <p>
 * M层：
 * 1.轮播图    （未完成，点击事件还没设置）
 * 2.综合栏目   （未完成，点击事件）
 * 3.推荐歌单     （未完成）
 * 4.音乐日历   （未完成）
 * <p>
 * B层：
 * 1.player
 * </p>
 */
public class MainFragment extends BaseFragment implements NavigationView.OnNavigationItemSelectedListener, IMainContract.View,
        MainViewPagerAdapter.OnReplaceable, NestedScrollView.OnScrollChangeListener {

    /**
     * 设置刷新头部的文字设置，静态初始化防止内存泄漏
     */
    static {
        // 头部设置
        ClassicsHeader.REFRESH_HEADER_PULLING = "使劲拉！";
        ClassicsHeader.REFRESH_HEADER_REFRESHING = "(～￣▽￣)～";
        ClassicsHeader.REFRESH_HEADER_LOADING = "加载中";
        ClassicsHeader.REFRESH_HEADER_RELEASE = "照了，摆拉了";
        ClassicsHeader.REFRESH_HEADER_FINISH = "刷新完成";
        ClassicsHeader.REFRESH_HEADER_FAILED = "刷新失败";
        ClassicsHeader.REFRESH_HEADER_UPDATE = "上次更新 M-d HH:mm";
    }

    private static final String TAG = "MainFragment";

    private MainActivity mActivity;

    /**
     * 侧滑栏
     */
    private DrawerLayout mDlLeftSlides; // 侧滑栏布局
    private NavigationView mNvLeftSlidesInside;  // 侧滑栏内布局

    /**
     * 轮播图相关
     */
    private Banner mBanner;
    private BannerImageAdapter adapter;
    private List<com.example.yan_music.bean.wangyi.Banner.BannersBean> mBannerList;
    private IMainPresenterImp iMainPresenterImp;

    /**
     * 综合栏相关
     */
    private LinearLayout mLlDayRecommend,   // 每日推荐
            mLlPersonalFM,     // 私人FM
            mLlSOngList,       //  歌单
            mLlLeaderBoard,    //  排行榜
            mLlNumAlbum,       //  数字专辑
            mLlLive,           //  直播
            mLlChat;           //  畅聊
    private TextView mTvCalendarDay; // 日期

    /**
     * toolbar相关
     */
    private RelativeLayout mRlSearch; // 搜索
    private ImageView mImgSettings; // 设置
    private CircleImageView mCivUserPic;    // 用户头像
    private MarqueeTextView mTvHotTip; // 暖心语

    /**
     * 滑动相关
     */
    private NestedScrollView mNestScrollView;
    private float viewY;    // player垂直平移的距离
    private boolean isAnimate;

    /**
     * player
     */
    private RelativeLayout mRlPlayer;

    /**
     * 推荐歌单
     */
    private List<RecommendSongList.ResultBean> mRecommendSongList;
    private RecyclerView mRcvRecommend;
    private RcvRecommendAdapter rcvRecommendAdapter;
    private TextView mRecommendMore;

    /**
     * 播放服务相关
     */
    private PlayerService.PlayBinder mPlayBinder;
    private ServiceConnection mServiceConnection;


    private FrameLayout sacnLayout;


    /**
     * 构造器
     */
    public MainFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        init(view);
        initListener();
        initBaseSettings();
        bindPlayService();
        StatusBarUtil.setStatusBarMode(mActivity, true, R.color.statusBarColor_main_white);
        // 设置状态栏为透明
        //StatusBarUtil.setTranslucentStatus(mActivity);
        showCalendarDay();
        showBanner();
        showRecommendSongLists();
        onClick(view);
        return view;
    }

    /**
     * 初始化View和基本设置
     *
     * @param view
     */
    @Override
    public void init(View view) {
        mActivity = (MainActivity) getActivity();
        iMainPresenterImp = new IMainPresenterImp();
        iMainPresenterImp.attachView(this);
        mTvHotTip = view.findViewById(R.id.toolbar_search_text);
        mBanner = view.findViewById(R.id.banner);
        mRlSearch = view.findViewById(R.id.toolbar_search);
        mLlDayRecommend = view.findViewById(R.id.ll_day_recommend);
        mLlPersonalFM = view.findViewById(R.id.ll_fm);
        mLlSOngList = view.findViewById(R.id.ll_song_list);
        mLlLeaderBoard = view.findViewById(R.id.ll_pai_hang_bang);
        mLlLive = view.findViewById(R.id.ll_live);
        mLlChat = view.findViewById(R.id.ll_chang_liao);
        mLlNumAlbum = view.findViewById(R.id.ll_shu_zi_zhuanji);
        mImgSettings = view.findViewById(R.id.toolbar_settings);
        mCivUserPic = view.findViewById(R.id.toolbar_user_pic);
        // 这里注意不能用传进来的view去fbi，因为这个布局是属于MainActivity的,而不是MainFragment的
        mDlLeftSlides = mActivity.findViewById(R.id.dl_sideslip_layout);
        mNvLeftSlidesInside = mActivity.findViewById(R.id.nv_sides_lip);
        mNestScrollView = view.findViewById(R.id.nv_fragment_main);
        mRlPlayer = mActivity.findViewById(R.id.rl_main_player);
        mTvCalendarDay = view.findViewById(R.id.tv_day);
        mRecommendMore = view.findViewById(R.id.tv_recommend_list_more);
        mRcvRecommend = view.findViewById(R.id.rcv_recommend_song_list);

         sacnLayout = view.findViewById(R.id.scan);

    }

    /**
     * 设置点击监听器
     */
    public void initListener() {
        mNvLeftSlidesInside.setNavigationItemSelectedListener(this);
        mImgSettings.setOnClickListener(this);
        mLlDayRecommend.setOnClickListener(this);
        mLlSOngList.setOnClickListener(this);
        mLlPersonalFM.setOnClickListener(this);
        mRlSearch.setOnClickListener(this);
        mLlLeaderBoard.setOnClickListener(this);
        mLlChat.setOnClickListener(this);
        mLlNumAlbum.setOnClickListener(this);
        mLlLive.setOnClickListener(this);
        mNestScrollView.setOnScrollChangeListener(this);
        mRecommendMore.setOnClickListener(this);
        mCivUserPic.setOnClickListener(this);
    }

    /**
     * 一些基础设置
     */
    public void initBaseSettings() {
        // 保留侧滑栏菜单里面子项icon原色
        mNvLeftSlidesInside.setItemIconTintList(null);
        // 注册EventBus
        //EventBus.getDefault().register(this);
        // 搜索布局里面的文字渐变颜色
        TextFontUtils.setGradientFont(mTvHotTip, "#FF6666", "#339999");
    }

    /**
     * 普通点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_search:
                // 点击搜索跳转到搜索页面
                EventBus.getDefault().post(new ReplaceViewPagerFragmentEvent(new SearchFragment()));
                // 检查菜单是否是打开状态
                mActivity.isCoverMenuOpen();
                // 更换player中tab1图标，文字
                mActivity.modifyPlayrTabOneIconAndText(R.drawable.tab_1_search_on, "搜索", R.color.tab1_on_color);
                break;
            case R.id.toolbar_settings:
                // 打开侧滑栏(从左边打开)
                mDlLeftSlides.openDrawer(Gravity.LEFT);
                mActivity.isCoverMenuOpen();
                break;

            //  推荐歌单点击事件
            case R.id.tv_recommend_list_more:
                XToast.showInfo("更多");
                break;
            case R.id.img_item_1:
                break;
            case R.id.img_item_2:
                break;
            case R.id.img_item_3:
                break;
            case R.id.img_item_4:
                break;
            case R.id.img_item_5:
                break;
            case R.id.img_item_6:
                break;

            // 综合栏点击事件
            case R.id.ll_day_recommend:
                break;
            case R.id.ll_fm:
                break;
            case R.id.ll_song_list:
                break;
            case R.id.ll_pai_hang_bang:
                break;
            case R.id.ll_shu_zi_zhuanji:
                break;
            case R.id.ll_live:
                break;
            case R.id.ll_chang_liao:
                break;

            // 头像点击事件
            case R.id.toolbar_user_pic:
                if(sacnLayout.getVisibility() == View.GONE){
                    sacnLayout.setVisibility(View.VISIBLE);
                    Animation a1 = AnimationUtils.loadAnimation(getContext(), R.anim.scan);
                    Animation a2 = AnimationUtils.loadAnimation(getContext(), R.anim.scan);
                    Animation a3 = AnimationUtils.loadAnimation(getContext(), R.anim.scan);
                    sacnLayout.findViewById(R.id.img_1).startAnimation(a1);

                    a2.setStartOffset(600);
                    sacnLayout.findViewById(R.id.img_2).startAnimation(a2);

                    a3.setStartOffset(1200);
                    sacnLayout.findViewById(R.id.img_3).startAnimation(a3);
                }else {
                    sacnLayout.setVisibility(View.GONE);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 侧滑栏中 NavigationView 的子项点击事件
     *
     * @param menuItem 菜单子项
     * @return
     */
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case R.id.nv_about:
                Toast.makeText(getContext(), "功能待做1", Toast.LENGTH_SHORT).show();
                mDlLeftSlides.closeDrawer(Gravity.LEFT);
                return true;
            case R.id.nv_1:
                Toast.makeText(getContext(), "功能待做2", Toast.LENGTH_SHORT).show();
                mDlLeftSlides.closeDrawer(Gravity.LEFT);
                return true;
            case R.id.nv_2:
                Toast.makeText(getContext(), "功能待做3", Toast.LENGTH_SHORT).show();
                mDlLeftSlides.closeDrawer(Gravity.LEFT);
                return true;
            default:
                break;
        }
        return false;
    }

    /**
     * 设置Banner
     *
     * @param bannerList
     */
    @Override
    public void setmBanner(List<com.example.yan_music.bean.wangyi.Banner.BannersBean> bannerList) {
        mBannerList = new ArrayList<>();
        mBannerList.addAll(bannerList);
        adapter = new BannerImageAdapter(mBannerList);
        mBanner.addBannerLifecycleObserver(this)
                // 设置轮播动画
                .addPageTransformer(new ZoomOutPageTransformer())
                .setAdapter(adapter)
                // 设置圆点指示器
                .setIndicator(new CircleIndicator(getContext()));
        // banner点击事件
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(Object data, int position) {
                // 根据targetType分类
                // 1:歌曲，有歌曲id，根据id点击直接播放
                // 3000:直播，有url，点击跳转网页
                com.example.yan_music.bean.wangyi.Banner.BannersBean item = (com.example.yan_music.bean.wangyi.Banner.BannersBean) data;
                Log.d(TAG, "OnBannerClick: " + item.getTargetType());
                if (item.getTargetType() == 1) {
                    // 歌曲id
                    int songId = item.getSong().getId();
                    Log.d(TAG, "OnBannerClick: " + songId);
                    // 歌曲名
                    String songName = item.getSong().getName();
                    // TODO 跳转到播放活动界面

                }

                if (item.getTargetType() == 3000) {
                    // 网页
                    String webUrl = (String) item.getUrl();
                    // TODO 请求网页
                }
            }
        });
    }

    /**
     * 设置推荐歌单
     *
     * @param songLists
     */
    @Override
    public void setRecommendSongLists(List<RecommendSongList.ResultBean> songLists) {
        mRecommendSongList = new ArrayList<>();
        mRecommendSongList.addAll(songLists);
        rcvRecommendAdapter = new RcvRecommendAdapter(mActivity, mRecommendSongList);
        rcvRecommendAdapter.setOnItemClickListener(new RcvRecommendAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                // 点击子项post“歌单详情”Fragemnt事件
                RecommendSongList.ResultBean songlist = mRecommendSongList.get(position);
                long listId = songlist.getId();
                String listName = songlist.getName();
                Log.d(TAG, "onItemClick: "
                        + "\n 歌单名=" + listName
                        + "\n 歌单id=" + listId);
                EventBus.getDefault().post(new ReplaceViewPagerFragmentEvent(new ListDetailFragment(listId)));
            }
        });
        mRcvRecommend.setLayoutManager(new GridLayoutManager(mActivity, 3));
        mRcvRecommend.addItemDecoration(new RcvSearchAdapter.ItemSpaceDecoration(26, 0, 0, 0));
        mRcvRecommend.setLayoutAnimation(AnimationUtils.loadLayoutAnimation(mActivity, R.anim.layout_anim_item_right_slipe));
        mRcvRecommend.setAdapter(rcvRecommendAdapter);
    }

    /**
     * 播放歌曲
     *
     * @param songUrl
     */
    @Override
    public void playSong(String songUrl) {
        mPlayBinder.playSong(songUrl);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Presenter解绑View
        iMainPresenterImp.detachView();
        // 解绑EventBus
        // EventBus.getDefault().unregister(this);
    }

    /**
     * 展示Banner
     */
    private void showBanner() {
        if (mBannerList == null) {
            iMainPresenterImp.getBanner();
        }
    }

    /**
     * 显示推荐菜单
     */
    private void showRecommendSongLists() {
        iMainPresenterImp.getRecommendSongLists();
    }

    /**
     * TODO 设置用户头像
     *
     * @param picUrl 用户头像url
     */
    private void showUserPic(String picUrl) {
        // 登没登录需要用cookie判断一下
        if (!SharePreferenceUtil.get(mActivity, "cookie", "").equals("")) {
            // cookie不为空，可以获取到用户头像
            Glide.with(mActivity)
                    .load(picUrl)
                    // 加载完成前的预览图
                    .placeholder(R.drawable.pre_user_pic)
                    .into(mCivUserPic);
        } else {
            Log.d(TAG, "setUserPic: " + "cookie为空，未登录，头像为空");
        }
    }

    /**
     * 监听NestScrollView的滑动
     *
     * @param v
     * @param scrollX    X滑动原点
     * @param scrollY    Y滑动原点
     * @param oldScrollX 上一个X滑动原点
     * @param oldScrollY 上一个Y滑动原点
     */
    @Override
    public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
        //Log.d(TAG, "onScrollChange: " + "scrollY = " + scrollY + "  oldScrollY = " + oldScrollY);
        // 垂直方向滚动的差值
        int dy = scrollY - oldScrollY;
        // Log.d(TAG, "onScrollChange: Y方向上的差值 = " + dy);
        if (dy > 0 && !mActivity.isAnimate()) {
            // 大于0表示上滑
            // 向下隐藏player
            mActivity.hidePlayer(mRlPlayer);
        } else if (dy < 0 && !mActivity.isAnimate()) {
            // 小于0表示下滑
            // 向上显示player
            mActivity.showPlayer(mRlPlayer);
        }
    }

    /**
     * 设置"每日推荐"中的日期
     */
    private void showCalendarDay() {
        int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
        mTvCalendarDay.setText("" + day + "");
    }

    /**
     * 绑定播放服务
     */
    private void bindPlayService() {
        mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                XLog.d(name + "》》》》》》》》》播放服务连接成功《《《《《《《《《《" + this.getClass().getName());
                mPlayBinder = (PlayerService.PlayBinder) service;
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                XLog.d(name + "服务断开连接");
            }
        };
        Intent intent = new Intent(getActivity(), PlayerService.class);
        getActivity().bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

}